/*
 * Copyright 2010 Katsunori Koyanagi
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package sweezy.anim
{
	import sweezy.anim.core.IAnimationGroupBuilder;

	public function group(animation:*, ... animations:*):IAnimationGroupBuilder
	{
		return new GroupAnimationBuilder(animation, animations);
	}
}

import sweezy.anim.animate;
import sweezy.anim.core.Animator;
import sweezy.anim.core.IAnimation;
import sweezy.anim.core.IAnimationBuilder;
import sweezy.anim.core.IAnimationGroupBuilder;
import sweezy.anim.core.IAnimationManager;

class GroupAnimationBuilder implements IAnimationGroupBuilder
{

	private var _animations:Array;

	public function GroupAnimationBuilder(animation:*, animations:Array)
	{
		_animations = [];

		for (var i:int = 0, len:uint = animations.length; i < len; i++)
		{
			add(animations[i]);
		}
	}

	public function add(animation:*):IAnimationGroupBuilder
	{
		var i:int, len:int;

		if (animation is Array)
		{
			for (i = 0, len = animation.length; i < len; i++)
			{
				add0(animation[i]);
			}
		}
		else if (animation is Vector)
		{
			for (i = 0, len = animation.length; i < len; i++)
			{
				add0(animation[i]);
			}
		}
		else if (animation is IAnimation)
		{
			add0(animation);
		}
		else if (animation is IAnimationBuilder)
		{
			add0(animation);
		}
		else if (animation is Object)
		{
			for (var key:Object in animation)
			{
				add0(animation[key]);
			}
		}

		return this;
	}

	public function get parallel():IAnimationBuilder
	{
		var manager:IAnimationManager = Animator.manager;
		return animate(manager.createParallelAnimation(_animations));
	}

	public function get serial():IAnimationBuilder
	{
		var manager:IAnimationManager = Animator.manager;
		return animate(manager.createSerialAnimation(_animations));
	}

	private function add0(animation:*):void
	{
		var anim:IAnimation;
		if (animation === null)
		{
			return;
		}
		if (animation is IAnimation)
		{
			anim = animation as IAnimation;
		}
		else if (animation is IAnimationBuilder)
		{
			anim = (animation as IAnimationBuilder).animation;
		}
		else
		{
			return;
		}

		_animations[_animations.length] = anim;
	}
}
